document.write('<script src="/js/vue.min.js" charset="utf-8"></script>');

layui.use(['jquery','layer'], function () {
    var $ = layui.jquery,layer=layui.layer;
    //全局错误提示
    $(document).ajaxComplete(function(event,request, settings){ //ajaxSuccess , ajaxComplete
        try{
            var res = request.responseJSON;
            if (typeof res.code ==='number' && res.code !== 0){
                layer.msg(res.msg,{icon:5})
            }
        }catch(e){}
    });

    //隐藏不拥有的权限
    var noAuthFlags = JSON.parse(localStorage.getItem('noAuthFlags'));
    var styleStr = '<style>';
    for(var k in noAuthFlags){
        var flag = noAuthFlags[k];
        styleStr += '[auth="'+flag+'"]{display:none;}';
    }
    styleStr += '</style>';
    $('body').append(styleStr);
})

window.settingSetVal = function(name,val,callback){
    layui.use(['jquery'], function () {
        var $ = layui.jquery;
        $.post('/admin/webManage/setting',{_method: 'put',name:name,val:val},function(res){
            if(callback) callback(res)
        });
    })
}


/**
 *  获取url参数
 * @param key
 */
function urlParam(key){
    var search = location.search.slice(1);
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == key) {
            if (encodeURI(ar[1]) == 'undefined') {
                return "";
            } else {
                return encodeURI(ar[1]);
            }
        }
    }
    return "";
}

function generateId(){ //生成唯一ID
    return ('_' + Math.random()).replace('.','')
}

function downloadText(file_name, content) {
    var csvData = new Blob([content], { type: 'text/csv' });
    // for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(csvData, file_name);
    }
    // for Non-IE (chrome, firefox etc.)
    else {
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.style = 'display: none';
        var url = window.URL.createObjectURL(csvData);
        a.href =  url;
        a.download = file_name;
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
    }
};
// 文件异步下载 , 要求header 有 Content-Type 和 Content-Disposition
function asyncDownload(url,params,headers,successCallback){
   var kvUrl = '';
    for(var k in params){
        var v = params[k];
        if (typeof v =='object'){
            v = encodeURIComponent(JSON.stringify(v))
        }
        if(v.toString().includes('\n')){
            v = v.toString().split('\n').join('%0A');
        }
        kvUrl += '&'+k +'='+ v;
    }
    url += '?' + kvUrl.substr(1);
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true); //打开请求
    for(var k in headers){
        var v = headers[k];
        xhr.setRequestHeader(k,v)
    }
    xhr.responseType = "blob";
    xhr.timeout = 0; // 设置超时时间,0表示永不超时
    xhr.onload = function () { //返回成功之后执行的方法 , 未下载完之前这里会阻塞
        var disposition = xhr.getResponseHeader('Content-Disposition');
        var hdArr = disposition.split("filename*=utf-8''");
        var fileName = decodeURI(hdArr[1]);
        //将文件流保存到a标签
        var content = this.response;
        // 组装a标签
        var elink = document.createElement("a");
        // 设置下载文件名
        elink.download = fileName;
        elink.style.display = "none";
        var blob = new Blob([content]);
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        if (successCallback) successCallback();
    }
    xhr.send();
}


// 文件异步下载 , 要求header 有 Content-Type 和 Content-Disposition
function asyncDownloadString(url,params,headers,successCallback){
    var kvUrl = '';
    for (var k in params) {
        var v = params[k];
        console.log(v)
        if (typeof v =='object'){
            v = encodeURIComponent(JSON.stringify(v))
        }
        kvUrl += '&' + k + '=' + v;
    }
    console.log('更新了')

    url += '?' + kvUrl.substr(1);
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true); //打开请求
    for(var k in headers){
        var v = headers[k];
        xhr.setRequestHeader(k,v)
    }
    xhr.responseType = "blob";
    xhr.timeout = 0; // 设置超时时间,0表示永不超时
    xhr.onload = function () { //返回成功之后执行的方法 , 未下载完之前这里会阻塞
        var disposition = xhr.getResponseHeader('Content-Disposition');
        var hdArr = disposition.split("filename*=utf-8''");
        var fileName = decodeURI(hdArr[1]);
        //将文件流保存到a标签
        var content = this.response;
        // 组装a标签
        var elink = document.createElement("a");
        // 设置下载文件名
        elink.download = fileName;
        elink.style.display = "none";
        var blob = new Blob([content]);
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        if (successCallback) successCallback();
    }
    xhr.send();
}
function getEnum(key){
    var obj = JSON.parse(localStorage.getItem('enums'));
    if (!obj) return null;
    return obj[key] || null;
}
function getYMDHMS(time) { //时间戳转换到年月日时分秒格式
    var myDate = new Date(time * 1000);
    var M, D, h, m, s;
    M = (myDate.getMonth() + 1) < 10 ? "0" + (myDate.getMonth() + 1) : myDate.getMonth() + 1;
    D = myDate.getDate() < 10 ? "0" + myDate.getDate() : myDate.getDate();
    h = myDate.getHours() < 10 ? "0" + myDate.getHours() : myDate.getHours();
    m = myDate.getMinutes() < 10 ? "0" + myDate.getMinutes() : myDate.getMinutes();
    s = myDate.getSeconds() < 10 ? "0" + myDate.getSeconds() : myDate.getSeconds();

    var YMD = myDate.getFullYear() + "-" + M + "-" + D;
    var HMS = h + ":" + m + ":" + s;
    return YMD + " " + HMS;
}

/** 获取当前时间的年月日
 * @param day 向后偏移的天数
 * @returns {string}
 */
function getYmd(day){
    var microTime = new Date().getTime() + day*24*3600000;
    var date = new Date(microTime);
    var sign2 = ":";
    var year = date.getFullYear() // 年
    var month = date.getMonth() + 1; // 月
    var day = date.getDate(); // 日
    var hour = date.getHours(); // 时
    var minutes = date.getMinutes(); // 分
    var seconds = date.getSeconds() //秒
    // 给一位数的数据前面加 “0”
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }
    if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    //return year + "-" + month + "-" + day + " " + hour + sign2 + minutes + sign2 + seconds;
    return year + "-" + month + "-" + day ;
}
function array_unique(arr) {
    var newArr = [...new Set(arr)]; //利用了Set结构不能接收重复数据的特点
    return newArr
}
function toEquipName(equipId) {
    var arr = getEnum('equip');
    for(var k in arr){
        if (arr[k].id == equipId){
            return arr[k].name;
        }
    }
    return '_' + equipId;
}

function browserDownload(url) { //使用浏览器下载
    layui.use([], function () {
        var $ = layui.$;
        var Id = '_'+new Date().getTime();
        $('body').append("<iframe id='"+Id+"' style='display: none;' src='"+url+"'></iframe>");
        setTimeout(function () {
            $('#'+Id).remove();
        },7200000);//2小时候删除 iframe
    });
}

function browserDownloadList(relativeUrl) {
    const baseUrl = window.location.origin; // 获取当前网页的域名
    const url = `${baseUrl}/${relativeUrl}`; // 拼接完整的下载链接

    fetch(url)
        .then(response => {
            if (!response.ok) throw new Error('Network response was not ok');
            return response.blob(); // 获取 Blob 对象
        })
        .then(blob => {
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob); // 创建下载链接
            link.download = relativeUrl.split('/').pop(); // 提取文件名
            document.body.appendChild(link);
            link.click(); // 自动点击链接下载
            link.remove(); // 点击后移除链接
        })
        .catch(error => console.error('下载出错:', error));
}